<template>
	<div class="app-container">
		<div class="search">
			<el-form ref="queryFormRef" :model="queryParams" :inline="true">
				<el-form-item label="关键字" prop="keywords">
					<el-input v-model="queryParams.keywords" placeholder="类目名称" clearable @keyup.enter="handleQuery" />
				</el-form-item>
				<el-form-item>
					<el-button type="primary" :icon="Search" @click="handleQuery">搜索</el-button>
					<el-button :icon="Refresh" @click="resetQuery">重置</el-button>
				</el-form-item>
			</el-form>
		</div>

		<!-- 数据表格 -->
		<el-card>
			<template #header>
				<el-button type="success" :icon="Plus" @click="handleAdd">新增</el-button>
			</template>
			<el-table v-loading="loading" :data="categories" highlight-current-row
				:tree-props="{ children: 'children', hasChildren: 'hasChildren' }" row-key="id" border default-expand-all>
				<el-table-column label="类目名称" prop="name" width="200">
				</el-table-column>
				<el-table-column label="层级" align="center" width="80" prop="level" />
				<el-table-column label="状态" align="center" width="150">
					<template #default="scope">
						<el-tag v-if="scope.row.visible === 1" type="success">显示</el-tag>
						<el-tag v-else type="info">隐藏</el-tag>
					</template>
				</el-table-column>
				<el-table-column label="排序" align="center" width="100" prop="sort" />
				<el-table-column label="创建人" align="center" width="100" prop="creator">
				</el-table-column>
				<el-table-column label="创建时间" align="center" width="200" prop="createTime">
				</el-table-column>
				<el-table-column label="更新人" align="center" width="100" prop="updater">
				</el-table-column>
				<el-table-column label="修改时间" align="center" width="200" prop="updateTime">
				</el-table-column>
				<el-table-column label="操作" align="center" width="200">
					<template #default="scope">
						<el-button type="success" link @click.stop="handleAdd(scope.row)" v-if="scope.row.level < 3">
							新增
						</el-button>
						<el-button type="primary" link @click.stop="handleUpdate(scope.row)">
							修改
						</el-button>
						<el-button type="danger" link v-if="canDelete(scope.row)" @click.stop="handleDelete(scope.row)">
							删除
						</el-button>
					</template>
				</el-table-column>
			</el-table>
		</el-card>
		<!-- dialog -->
		<el-dialog :title="dialog.title" v-model="dialog.visible" @close="cancel" width="750px">
			<el-form ref="dataFormRef" :model="formData" :rules="rules" label-width="100px">
				<el-form-item label="父级类目" prop="parentId">
					<el-input v-model="formData.parentName" disabled />
				</el-form-item>
				<el-form-item label="类目名称" prop="name">
					<el-input v-model="formData.name" placeholder="请输入类目名称" />
				</el-form-item>
				<el-form-item label="类目层级" prop="level">
					<el-input v-model="formData.level" disabled />
				</el-form-item>
				<el-form-item label="状态">
					<el-radio-group v-model="formData.visible">
						<el-radio :label="1">显示</el-radio>
						<el-radio :label="0">隐藏</el-radio>
					</el-radio-group>
				</el-form-item>
				<el-form-item label="排序" prop="sort">
					<el-input-number v-model="formData.sort" style="width: 100px" controls-position="right" :min="0" />
				</el-form-item>
			</el-form>
			<template #footer>
				<div class="dialog-footer">
					<el-button type="primary" @click="submitForm">确 定</el-button>
					<el-button @click="cancel">取 消</el-button>
				</div>
			</template>
		</el-dialog>
</div>
</template>
<script setup lang="ts">
import { reactive, ref, onMounted, toRefs } from 'vue';

import { Search, Plus, Refresh } from '@element-plus/icons-vue';
import { ElForm, ElMessage, ElMessageBox } from 'element-plus';

// API 依赖
import {
	listCategories,
	addCategory,
	updateCategory,
	deleteCategories,
} from '@/api/pms/category';
import { Category, CategoryForm } from '@/api/pms/category/types';

const queryFormRef = ref(ElForm);
const dataFormRef = ref(ElForm);

const table = reactive({
	loading: true,
	// 选中ID数组
	ids: [],
	queryParams: {
		keywords: undefined
	},
	categories: [] as Category[],
});

const {
	loading,
	queryParams,
	categories,
} = toRefs(table);

const form = reactive({
	dialog: { visible: false } as DialogType,
	formData: {
		id: undefined,
		name: "",
		parentId: 0,
		parentName: "顶级类目",
		level: 1,
		iconUrl: undefined,
		sort: 100,
		visible: 1
	} as CategoryForm,
	rules: {
		parentId: [{ required: true, message: '请选择上级类目', trigger: 'blur' }],
		name: [{ required: true, message: '请输入类目名称', trigger: 'blur' }],
	},
});
const { formData, dialog, rules } = toRefs(form);

/**
 * 查询
 */
function handleQuery() {
	table.loading = true;
	listCategories(table.queryParams).then(({ data }) => {
		table.categories = data;
		table.loading = false;
	});
}

/**
 * 重置查询
 */
function resetQuery() {
	queryFormRef.value.resetFields();
	handleQuery();
}

/**
 * 新增类目
 */
async function handleAdd(row: any) {
	if (row.id) {
		formData.value.parentId = row.id;
		formData.value.parentName = row.name;
		formData.value.level = row.level + 1;
	}
	dialog.value = {
		title: '添加类目',
		visible: true,
	};
}

/**
 * 编辑类目
 */
function handleUpdate(row: Category) {
	const parent: { categoryName: string } = {
		categoryName: "顶级类目"
	}
	getParentCategoryName(row, categories.value, parent);
	formData.value.id = row.id;
	formData.value.name = row.name;
	formData.value.parentId = row.parentId;
	formData.value.parentName = parent.categoryName;
	formData.value.level = row.level;
	formData.value.iconUrl = row.iconUrl;
	formData.value.sort = row.sort;
	formData.value.visible = row.visible;
	dialog.value = {
		title: '编辑类目',
		visible: true,
	};
}

function getParentCategoryName(category: Category, categories: Category[], res: { categoryName: string }) {
	if (category.level === 1) {
		res.categoryName = "顶级类目";
		return;
	}
	if (!categories || categories.length === 0) {
		return;
	}
	if (categories[0].level > category.level - 1) {
		return;
	}
	if (categories[0].level < category.level - 1) {
		for (const c of categories) {
			getParentCategoryName(category, c.children, res);
		}
	}
	const target: Category | undefined = categories.find(c => c.id === category.parentId);
	if (target) {
		res.categoryName = target.name;
	}
}

function canDelete(row: Category) {
	return !(row.children && row.children.length > 0);
}


/**
 * 提交表单
 */
function submitForm() {
	dataFormRef.value.validate((isValid: boolean) => {
		if (isValid) {
			if (form.formData.id) {
				updateCategory(form.formData.id, form.formData).then(() => {
					ElMessage.success('修改成功');
					cancel();
					handleQuery();
				});
			} else {
				addCategory(form.formData).then(() => {
					ElMessage.success('新增成功');
					cancel();
					handleQuery();
				});
			}
		}
	});
}

/**
 * 删除菜单
 *
 * @param row
 */
function handleDelete(row: Category) {
	if (!row.id) {
		ElMessage.success('删除异常');
		return;
	}
	const ids: string = row.id.toString();
	ElMessageBox.confirm('确认删除已选中的数据项?', '警告', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning',
	})
		.then(() => {
			deleteCategories(ids).then(() => {
				ElMessage.success('删除成功');
				handleQuery();
			});
		})
		.catch(() => ElMessage.info('已取消删除'));
}

/**
 * 取消关闭弹窗
 */
function cancel() {
	dataFormRef.value.resetFields();
	form.dialog.visible = false;
}

onMounted(() => {
	handleQuery();
});
</script>